package com.gaiso.gaisopush.utils;

import android.content.Context;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by WangDongJie on 2017/4/21.
 */

public class FileUtil {

    public final static String APP_DATA_PATH = "gaisopush";
    private static ExecutorService mExecutor = Executors.newSingleThreadExecutor();

    public static void saveToFile(final String path, final String fileName, final String content) {
        mExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    if (isSDMounted()) {
                        File file = new File(path, fileName);
                        FileOutputStream fos = new FileOutputStream(file, true);
                        fos.write(content.getBytes());
                        fos.close();
                    }
                } catch (Exception e) {
                }
            }
        });
    }

    public static void saveLog(String path, String content) {
        saveToFile(path, "push.log", content);
    }

    private static boolean isSDMounted() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public static String getAppDataPath(Context context) {
        // 判断是否挂载了SD卡
        String dataPath = null;
        if (isSDMounted()) {
            dataPath = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator
                    + APP_DATA_PATH
                    + File.separator;
        } else {
            File basePath = context.getApplicationContext().getFilesDir();
            if (basePath == null) {
                basePath = context.getApplicationContext().getCacheDir();
            }
            dataPath = basePath.getAbsolutePath()
                    + File.separator
                    + APP_DATA_PATH
                    + File.separator;
        }
        File file = new File(dataPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        return dataPath;
    }
}
